package com.onlookers.server;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class User {
	public String subReport;

	private String subReportTime;

	public Set<String> keyWords = new HashSet<String>();

	public String email;

	public String phoneNum;

	public User(String subReport, String subReportTime, String email,
			String phoneNum) {
		this.subReport = subReport;
		this.subReportTime = subReportTime;
		this.email = email;
		this.phoneNum = phoneNum;

		Report.genKeyWords(subReport, keyWords);
	}

	public void pushReport(Report r) {
		pushMsg(r.toString(), r.toString());
	}

	public void pushReport(List<Report> reports) {
		StringBuilder sb = new StringBuilder();
		String smsmsg = null;
		for (Report r : reports) {
			sb.append(r.toString());
			if (smsmsg == null)
			smsmsg = r.toString();
		}
		
		if (reports.size() > 1) {
			smsmsg += (reports.size() - 1) + " message left...";
		}
		pushMsg(sb.toString(), smsmsg);
	}

	public void pushMsg(String msg, String smsmsg) {
		String url = "http://localhost/bcms-php-demo/index.php";

		System.out.println(phoneNum);
		System.out.println(email);
		System.out.println(msg);
		System.out.println(smsmsg);

		Map<String, String> params = new HashMap<String, String>();
		params.put("phone", phoneNum);
		params.put("email", email);
		params.put("msg", msg);
		if (smsmsg.length() > 70) {
			smsmsg = smsmsg.substring(0, 60);
		}
		params.put("smsmsg", smsmsg);
		
		
		post(url, params);
	}

	public static int post(String url, Map<String, String> param) {
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		for (String key : param.keySet()) {
			String value = String.valueOf(param.get(key));
			formparams.add(new BasicNameValuePair(key, value));
		}

		UrlEncodedFormEntity entity = null;
		try {
			entity = new UrlEncodedFormEntity(formparams, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		HttpPost httppost = new HttpPost(url);

		httppost.setEntity(entity);
		HttpClient client = new DefaultHttpClient();
		try {
			return client.execute(httppost).getStatusLine().getStatusCode();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return -1;
	}

}
